﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShoppingCart;

namespace CSE445HW5.UserProtected
{
    public partial class ShopCalculator : System.Web.UI.UserControl
    {
        double taxRate;
        double taxAmt;
        List<string> nameList;
        List<double> priceList;
        List<int> quantityList;

        /*
         * When the page loads, initialize the global variables. 
         */
        protected void Page_Load(object sender, EventArgs e)
        {
            taxRate = 0.1;
            taxAmt = 0;
            nameList = (List<string>)Session["nameList"];
            priceList = (List<double>)Session["priceList"];
            quantityList = (List<int>)Session["quantityList"];
            if (nameList == null || priceList == null || quantityList == null)
            {
                nameList = new List<string>();
                priceList = new List<double>();
                quantityList = new List<int>();
            }
            else
            {
                if (!IsPostBack)
                {
                    refreshItemList();
                    calculate();
                }
            }
        }

        /*
         * Event handler for adding an item.
         */
        protected void add_Button_Clicked(object sender, EventArgs e)
        {
            try
            {
                // Get the name, price and quantity of an item
                string name = itemBox.Text;
                double price = double.Parse(priceBox.Text);
                int quantity = int.Parse(quantBox.Text);

                // Add to lists
                nameList.Add(name);
                priceList.Add(price);
                quantityList.Add(quantity);

                refreshItemList();
                calculate();
                saveSession();
            }
            catch (FormatException ex)
            {
                Response.Write(ex.Message);
            }
        }

        /*
         * Event handler for removing items from the list.
         */
        protected void remove_Button_Clicked(object sender, EventArgs e)
        {
            int index = itemList.SelectedIndex;
            if (index >= 0)
            {
                nameList.RemoveAt(index);
                priceList.RemoveAt(index);
                quantityList.RemoveAt(index);
                refreshItemList();
                calculate();
                saveSession();
            }
            else
            {
                Response.Write("Please select an item from the list for removal.");
            }
        }

        /*
         * Event handler for clearing the list.
         */
        protected void clear_Button_Clicked(object sender, EventArgs e)
        {
            nameList.Clear();
            priceList.Clear();
            quantityList.Clear();
            refreshItemList();
            calculate();
            saveSession();
        }

        /*
         * Event handler for confirming a zipcode.
         */
        protected void confirm_Button_Click(object sender, EventArgs e)
        {
            shopCalculatorService.IshopCalculatorClient client = new shopCalculatorService.IshopCalculatorClient();
            string zipcode = zipBox.Text;
            taxRate = client.getTax(zipcode);
            stateLbl.Text = "State: " + client.getState(zipcode);
            calculate();
        }

        /*
         * This function will refresh the item list.
         */
        protected void refreshItemList()
        {
            itemList.Items.Clear();
            string toItemList = "";

            for (int i = 0; i < nameList.Count; i++)
            {
                toItemList = nameList[i] + " Qty: " + quantityList[i];
                itemList.Items.Add(toItemList);
            }
        }

        /*
         * This function will calculate the subtotal, tax amount and total.
         */
        protected void calculate()
        {
            Calculator calculator = new Calculator();
            List<double> prices = new List<double>();
            for (int i = 0; i < priceList.Count; i++)
            {
                prices.Add(calculator.itemPrice(priceList[i], quantityList[i]));
            }
            double subtotal = calculator.subTotCalc(prices.ToArray());
            subtotLblOut.Text = string.Format("{0:c}", subtotal);
            taxLblOut.Text = string.Format("{0:p}", taxRate);
            taxAmt = subtotal * taxRate;
            taxAmtLblOut.Text = string.Format("{0:c}", taxAmt);
            double total = subtotal + taxAmt;
            totalLblOut.Text = string.Format("{0:c}", total);
        }

        /*
         * This function saves the lists to the session.
         */
        protected void saveSession()
        {
            Session["nameList"] = nameList;
            Session["priceList"] = priceList;
            Session["quantityList"] = quantityList;
        }
    }
}